/*
 * InterfaceServeurAboutBox.java
 */
package interfaceserveur;

import gestionbdd.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import org.jdesktop.application.Action;

public class InterfaceEmployes extends javax.swing.JDialog implements InterfaceBDD {

    private DefaultListModel listeMissionModel;
    private javax.swing.JList listeMissions;
    private DAOMission dao;
    private DAOUtilisateur utilisateurDAO;

    public InterfaceEmployes(java.awt.Frame parent, javax.swing.JList liste, DAOMission dao) throws SQLException {
        super(parent);
        utilisateurDAO = (DAOUtilisateur) DAOFactory.getDAOUtilisateur();
        this.dao = dao;
        initComponents();
        listeMissions = liste;
        listeMissionModel = (DefaultListModel) listeMissions.getModel();
        messageAssignerMission.setText((String) listeMissionModel.getElementAt(listeMissions.getSelectedIndex()));
        getRootPane().setDefaultButton(boutonAjouterEmploye);
    }

    @Action
    public void fermerFenetre() {
        dispose();
    }

    private void clignoterMessage(final javax.swing.JLabel message) {
        message.setVisible(false);
        new Thread() {

            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
                message.setVisible(rootPaneCheckingEnabled);
            }
        }.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.JLabel imageLabel = new javax.swing.JLabel();
        PanneauListeEmployes = new javax.swing.JScrollPane();
        listeEmployes = new javax.swing.JList();
        champLogin = new javax.swing.JTextField();
        labelLogin = new javax.swing.JLabel();
        labelMotdePasse = new javax.swing.JLabel();
        labelTerminalAssigne = new javax.swing.JLabel();
        javax.swing.JLabel labelDescriptionMission = new javax.swing.JLabel();
        boutonAssignerMission = new javax.swing.JButton();
        labelListeMissionsAssignees = new javax.swing.JLabel();
        boutonSupprimerEmploye = new javax.swing.JButton();
        boutonAjouterEmploye = new javax.swing.JButton();
        champMotdePasseCrypte = new javax.swing.JPasswordField();
        messageVeuillezRemplirChamps = new javax.swing.JLabel();
        labelNouvelleMissionAssignee = new javax.swing.JLabel();
        messageAssignerMission = new javax.swing.JLabel();
        champTerminalAssigne = new javax.swing.JLabel();
        messageSelectEmploye = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance().getContext().getResourceMap(InterfaceEmployes.class);
        setTitle(resourceMap.getString("title")); // NOI18N
        setModal(true);
        setName("aboutBox"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N
        imageLabel.setName("imageLabel"); // NOI18N

        PanneauListeEmployes.setName("PanneauListeEmployes"); // NOI18N

        DefaultListModel listeEmployesModel = new DefaultListModel();
        for (int i=0; i < utilisateurDAO.findList().size();i++)
        {
            listeEmployesModel.addElement(utilisateurDAO.findList().get(i).getLogin());
        }
        listeEmployes.setModel(listeEmployesModel);
        listeEmployes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listeEmployes.setName("listeEmployes"); // NOI18N
        PanneauListeEmployes.setViewportView(listeEmployes);

        champLogin.setText(resourceMap.getString("champLogin.text")); // NOI18N
        champLogin.setName("champLogin"); // NOI18N

        labelLogin.setText(resourceMap.getString("labelLogin.text")); // NOI18N
        labelLogin.setName("labelLogin"); // NOI18N

        labelMotdePasse.setText(resourceMap.getString("labelMotdePasse.text")); // NOI18N
        labelMotdePasse.setName("labelMotdePasse"); // NOI18N

        labelTerminalAssigne.setText(resourceMap.getString("labelTerminalAssigne.text")); // NOI18N
        labelTerminalAssigne.setName("labelTerminalAssigne"); // NOI18N

        labelDescriptionMission.setFont(labelDescriptionMission.getFont().deriveFont(labelDescriptionMission.getFont().getStyle() | java.awt.Font.BOLD, labelDescriptionMission.getFont().getSize()+4));
        labelDescriptionMission.setText(resourceMap.getString("labelDescriptionMission.text")); // NOI18N
        labelDescriptionMission.setName("labelDescriptionMission"); // NOI18N

        boutonAssignerMission.setText(resourceMap.getString("boutonAssignerMission.text")); // NOI18N
        boutonAssignerMission.setName("boutonAssignerMission"); // NOI18N
        boutonAssignerMission.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonAssignerMissionActionPerformed(evt);
            }
        });

        labelListeMissionsAssignees.setText(resourceMap.getString("labelListeMissionsAssignees.text")); // NOI18N
        labelListeMissionsAssignees.setName("labelListeMissionsAssignees"); // NOI18N

        boutonSupprimerEmploye.setText(resourceMap.getString("boutonSupprimerEmploye.text")); // NOI18N
        boutonSupprimerEmploye.setName("boutonSupprimerEmploye"); // NOI18N
        boutonSupprimerEmploye.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonSupprimerEmployeActionPerformed(evt);
            }
        });

        boutonAjouterEmploye.setText(resourceMap.getString("boutonAjouterEmploye.text")); // NOI18N
        boutonAjouterEmploye.setName("boutonAjouterEmploye"); // NOI18N
        boutonAjouterEmploye.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boutonAjouterEmployeActionPerformed(evt);
            }
        });

        champMotdePasseCrypte.setText(resourceMap.getString("champMotdePasseCrypte.text")); // NOI18N
        champMotdePasseCrypte.setName("champMotdePasseCrypte"); // NOI18N

        messageVeuillezRemplirChamps.setFont(resourceMap.getFont("messageVeuillezRemplirChamps.font")); // NOI18N
        messageVeuillezRemplirChamps.setText(resourceMap.getString("messageVeuillezRemplirChamps.text")); // NOI18N
        messageVeuillezRemplirChamps.setName("messageVeuillezRemplirChamps"); // NOI18N
        messageVeuillezRemplirChamps.setVisible(false);

        labelNouvelleMissionAssignee.setText(resourceMap.getString("labelNouvelleMissionAssignee.text")); // NOI18N
        labelNouvelleMissionAssignee.setName("labelNouvelleMissionAssignee"); // NOI18N

        messageAssignerMission.setFont(resourceMap.getFont("messageAssignerMission.font")); // NOI18N
        messageAssignerMission.setText(resourceMap.getString("messageAssignerMission.text")); // NOI18N
        messageAssignerMission.setName("messageAssignerMission"); // NOI18N

        champTerminalAssigne.setText(resourceMap.getString("champTerminalAssigne.text")); // NOI18N
        champTerminalAssigne.setName("champTerminalAssigne"); // NOI18N

        messageSelectEmploye.setFont(resourceMap.getFont("messageSelectEmploye.font")); // NOI18N
        messageSelectEmploye.setText(resourceMap.getString("messageSelectEmploye.text")); // NOI18N
        messageSelectEmploye.setName("messageSelectEmploye"); // NOI18N
        messageSelectEmploye.setVisible(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(labelDescriptionMission)
                .addContainerGap(553, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(PanneauListeEmployes, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)
                    .addComponent(boutonSupprimerEmploye, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelListeMissionsAssignees)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 220, Short.MAX_VALUE)
                                .addComponent(labelTerminalAssigne)
                                .addGap(3, 3, 3)
                                .addComponent(champTerminalAssigne))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(79, 79, 79)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(labelMotdePasse)
                                            .addComponent(labelLogin))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(champLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                                            .addComponent(champMotdePasseCrypte, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE)
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                                .addGap(10, 10, 10)
                                                .addComponent(boutonAjouterEmploye))))
                                    .addGroup(layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(messageVeuillezRemplirChamps))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelNouvelleMissionAssignee)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(messageAssignerMission))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(114, 114, 114)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(messageSelectEmploye)
                            .addComponent(boutonAssignerMission, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(25, 25, 25))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelDescriptionMission)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(champLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(labelLogin))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(labelMotdePasse)
                                    .addComponent(champMotdePasseCrypte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(boutonAjouterEmploye)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(messageVeuillezRemplirChamps))
                            .addComponent(imageLabel))
                        .addGap(34, 34, 34)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelListeMissionsAssignees)
                            .addComponent(labelTerminalAssigne)
                            .addComponent(champTerminalAssigne))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(labelNouvelleMissionAssignee)
                            .addComponent(messageAssignerMission))
                        .addGap(18, 18, 18)
                        .addComponent(boutonAssignerMission, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(PanneauListeEmployes, javax.swing.GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(boutonSupprimerEmploye)
                    .addComponent(messageSelectEmploye))
                .addGap(14, 14, 14))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void boutonAjouterEmployeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boutonAjouterEmployeActionPerformed
        // Ajout d'un nouvel employé.
        DefaultListModel listeEmployesModel = (DefaultListModel) listeEmployes.getModel();
        boolean employeExistant = false;

        if (champLogin.getText().isEmpty() || champMotdePasseCrypte.getPassword().length == 0) {
            //gestion message d'erreur
            if (champLogin.getText().isEmpty() && champMotdePasseCrypte.getPassword().length == 0) {
                messageVeuillezRemplirChamps.setText("Veuillez remplir les champs!");
            } else if (champLogin.getText().isEmpty()) {
                messageVeuillezRemplirChamps.setText("Veuillez mettre un login!");
            } else {
                messageVeuillezRemplirChamps.setText("Veuillez mettre un mot de passe!");
            }


            //pour faire apparaitre ou clignoter le message d'erreur
            clignoterMessage(messageVeuillezRemplirChamps);
        } else {
            // condition si employé déjà existant
            for (int i = 0; i < listeEmployesModel.getSize(); i++) {
                if (listeEmployesModel.getElementAt(i).equals(champLogin.getText())) {
                    employeExistant = true;
                }
            }

            if (employeExistant == true) //si l'employé est déjà dans la liste, on le l'ajoute pas.
            {
                clignoterMessage(messageVeuillezRemplirChamps);
                messageVeuillezRemplirChamps.setText("Employé(e) déjà existant");
                messageVeuillezRemplirChamps.setVisible(true);
            } else //ajout de l'employé
            {
                messageVeuillezRemplirChamps.setVisible(false); // on enlève le message d'erreur au cas où il serait affiché.

                listeEmployesModel.addElement(champLogin.getText());  //ajout dans la liste
                AjouterEmployeBDD(champLogin.getText(), champMotdePasseCrypte.getPassword());  //ajout dans BDD


                //Vidage des champs
                champLogin.setText(null);
                champMotdePasseCrypte.setText(null);
                champTerminalAssigne.setText(null);
            }

        }

    }//GEN-LAST:event_boutonAjouterEmployeActionPerformed

    private void boutonSupprimerEmployeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boutonSupprimerEmployeActionPerformed
        //supprime de la liste l'employé sélectionné.
        int index = listeEmployes.getSelectedIndex();
        DefaultListModel listeEmployesModel = (DefaultListModel) listeEmployes.getModel();

        // A FAIRE : Rajouter confirmation!


        //On retire l'employé sélectionné de la liste,
        //si la liste est vide (exception), on ne fait rien.
        try {
            RetirerEmployeBDD((String) listeEmployesModel.getElementAt(index)); //Retrait dans la base de données
            listeEmployesModel.removeElementAt(index); //retrait dans la liste
        } catch (Exception e) {
        }



    }//GEN-LAST:event_boutonSupprimerEmployeActionPerformed

    private void boutonAssignerMissionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boutonAssignerMissionActionPerformed
        // TODO add your handling code here:
        int indexMission = listeMissions.getSelectedIndex();
        int indexEmployes = listeEmployes.getSelectedIndex();
        try {
            DefaultListModel listeEmployesModel = (DefaultListModel) listeEmployes.getModel();
            messageSelectEmploye.setVisible(false); //message d'erreur enlevé
            LierEmployeAMission((String) listeEmployesModel.getElementAt(indexEmployes),(String) listeMissionModel.getElementAt(indexMission));
            System.out.println("Pour toi");
            fermerFenetre();
        } catch (Exception e) {
            messageSelectEmploye.setVisible(true); //message d'erreur affiché
        }


    }//GEN-LAST:event_boutonAssignerMissionActionPerformed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        // TODO add your handling code here:
        messageAssignerMission.setText((String) listeMissionModel.getElementAt(listeMissions.getSelectedIndex()));
    }//GEN-LAST:event_formWindowActivated
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane PanneauListeEmployes;
    private javax.swing.JButton boutonAjouterEmploye;
    private javax.swing.JButton boutonAssignerMission;
    private javax.swing.JButton boutonSupprimerEmploye;
    private javax.swing.JTextField champLogin;
    private javax.swing.JPasswordField champMotdePasseCrypte;
    private javax.swing.JLabel champTerminalAssigne;
    private javax.swing.JLabel labelListeMissionsAssignees;
    private javax.swing.JLabel labelLogin;
    private javax.swing.JLabel labelMotdePasse;
    private javax.swing.JLabel labelNouvelleMissionAssignee;
    private javax.swing.JLabel labelTerminalAssigne;
    private javax.swing.JList listeEmployes;
    private javax.swing.JLabel messageAssignerMission;
    private javax.swing.JLabel messageSelectEmploye;
    private javax.swing.JLabel messageVeuillezRemplirChamps;
    // End of variables declaration//GEN-END:variables

    public void AjouterEmployeBDD(String login, char[] motDePasse) {
        Utilisateur user = new Utilisateur(login, String.copyValueOf(motDePasse), -1);
        try {
            DAOFactory.getDAOUtilisateur().create(user);
        } catch (SQLException ex) {
            Logger.getLogger(InterfaceEmployes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void RetirerEmployeBDD(String login) {
        Utilisateur user = new Utilisateur(login, "", -1);
        try {
            DAOFactory.getDAOUtilisateur().delete(user);
        } catch (SQLException ex) {
            Logger.getLogger(InterfaceEmployes.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void AjouterMissionBDD() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void RetirerMissionBDD() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    private void LierEmployeAMission(String nomUti , String idMission) {
        int id = Integer.parseInt(idMission);
            Mission mission = dao.find(id);
            mission.setUtilisateur(nomUti);
            dao.update(mission);
    }
}
